|
clone() is a method in the Java programming language for object duplication. In Java, objects are manipulated through reference variables, and there is no operator for ''copying'' an object—the assignment operator duplicates the reference, not the object. The clone() method provides this missing functionality.== Overview == Classes that want copying functionality must implement some method to do so. To a certain extent that function is provided by " Object.clone() ". clone() acts like a copy constructor. Typically it calls the clone() method of its superclass to obtain the copy, etc. until it eventually reaches Object 's clone() method. The special clone() method in the base class Object provides a standard mechanism for duplicating objects.The class Object 's clone() method creates and returns a copy of the object, with the same class and with all the fields having the same values. However, Object.clone() throws a CloneNotSupportedException unless the object is an instance of a class that implements the marker interface Cloneable .The default implementation of Object.clone() performs a shallow copy. When a class desires a deep copy or some other custom behavior, they must perform that in their own clone() method after they obtain the copy from the superclass.The syntax for calling clone in Java is (assuming obj is a variable of a class type that has a public clone() method):or commonly which provides the typecasting needed to assign the general Object reference returned from clone to a reference to a MyClass object.One disadvantage with the design of the clone() method is that the return type of clone() is Object , and needs to be explicitly cast back into the appropriate type. However, overriding clone() to return the appropriate type is preferable and eliminates the need for casting in the client (using covariant return types, since J2SE 5.0).Another disadvantage is that one often cannot access the clone() method on an abstract type. Most interfaces and abstract classes in Java do not specify a public clone() method. As a result, often the clone() method can only be used if the actual class of an object is known, which is contrary to the abstraction principle of using the most generic type possible. For example, if one has a List reference in Java, one cannot invoke clone() on that reference because List specifies no public clone() method. Actual implementations of List like ArrayList and LinkedList all generally have clone() methods themselves, but it is inconvenient and bad abstraction to carry around the actual class type of an object.抄文引用元・出典: フリー百科事典『 ウィキペディア(Wikipedia)』 ■ウィキペディアで「Clone (Java method)」の詳細全文を読む スポンサード リンク
|